<!-- 还款查询 -->
<template>
	<a-card :bordered="false">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<a-row :gutter="24"
				><!--表示一行-->
				<a-col :span="5">
					<a-form-item label="业务号" name="businessId">
						<a-input v-model:value="searchFormState.businessId" placeholder="请输入业务号" allow-clear />
					</a-form-item>
				</a-col>
				<a-col :span="7">
					<a-form-item label="接收时间" name="createTime">
						<a-range-picker
							v-model:value="searchFormState.createTime"
							valueFormat="YYYY-MM-DD HH:mm:ss"
							:allowClear="false"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-button type="primary" @click="table.refresh(true)">查询</a-button>
					<a-button style="margin: 0 8px" @click="reset">重置</a-button>
				</a-col>
			</a-row>
			<a-row>
				<a-button type="primary" @click="exportexcel">导出</a-button>
			</a-row>
		</a-form>
		<s-table
			ref="table"
			:columns="columns"
			:data="loadData"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
		>
			<template #operator class="table-operator">
				<a-space>
					<a-button type="primary" @click="formRef.onOpen()" v-if="hasPerm('dataWxjkHksjAdd')">
						<template #icon>
							<plus-outlined />
						</template>
						新增
					</a-button>
					<xn-batch-button
						v-if="hasPerm('dataWxjkHksjBatchDelete')"
						buttonName="批量删除"
						icon="DeleteOutlined"
						:selectedRowKeys="selectedRowKeys"
						@batchCallBack="deleteBatchDataWxjkHksj"
					/>
				</a-space>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'action'">
					<a-space>
						<a @click="formRef.onOpen(record)" v-if="hasPerm('dataWxjkHksjEdit')">编辑</a>
						<a-divider type="vertical" v-if="hasPerm(['dataWxjkHksjEdit', 'dataWxjkHksjDelete'], 'and')" />
						<a-popconfirm title="确定要删除吗？" @confirm="deleteDataWxjkHksj(record)">
							<a-button type="link" danger size="small" v-if="hasPerm('dataWxjkHksjDelete')">删除 </a-button>
						</a-popconfirm>
					</a-space>
				</template>
			</template>
		</s-table>
	</a-card>
	<Form ref="formRef" @successful="table.refresh(true)" />
</template>

<script setup name="dataWxjkHksjForm">
	import Form from './form.vue'
	import dataWxjkHksjApi from '@/api/tjzy/repaymentQuery/dataWxjkHksjApi'
	import dayjs from 'dayjs'
	// import utc from 'dayjs/plugin/utc'
	// import timezone from 'dayjs/plugin/timezone'
	//
	// dayjs.extend(utc)
	// dayjs.extend(timezone)
	// dayjs.tz.setDefault('Asia/Shanghai') // 设置默认时区为上海

	let searchFormState = reactive({
		createTime: [
			dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
			dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss')
		]
	})
	const searchFormRef = ref()
	const table = ref()
	const formRef = ref()
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }
	const columns = [
		{
			title: '业务号',
			dataIndex: 'businessId'
		},
		{
			title: '入账时间',
			dataIndex: 'accountDate'
		},
		{
			title: '已还金额',
			dataIndex: 'realAmount'
		},
		{
			title: '逾期金额',
			dataIndex: 'overdueAmount'
		},
		{
			title: '是否减免金额',
			dataIndex: 'activeRepayment'
		},
		{
			title: '调解员姓名',
			dataIndex: 'seatName'
		},
		{
			title: '所属部门',
			dataIndex: 'deptName'
		},
		{
			title: '接收时间',
			dataIndex: 'createTime'
		}
	]
	// 操作栏通过权限判断是否显示
	if (hasPerm(['dataWxjkHksjEdit', 'dataWxjkHksjDelete'])) {
		columns.push({
			title: '操作',
			dataIndex: 'action',
			align: 'center',
			width: '150px'
		})
	}
	// searchFormState.createTime = [dayjs().startOf('day'), dayjs().endOf('day')]
	const selectedRowKeys = ref([])
	// 列表选择配置
	const options = {
		// columns数字类型字段加入 needTotal: true 可以勾选自动算账
		alert: {
			show: true,
			clear: () => {
				selectedRowKeys.value = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}
	const exportexcel = () => {
		const searchFormParamExport = JSON.parse(JSON.stringify(searchFormState))
		if (searchFormParamExport.createTime) {
			searchFormParamExport.startCreateTime = searchFormParamExport.createTime[0]
			searchFormParamExport.endCreateTime = searchFormParamExport.createTime[1]
			delete searchFormParamExport.createTime
		}

		dataWxjkHksjApi.dataWxjkHksjExport(searchFormParamExport).then((res) => {
			// 创建一个 URL 对象用于临时访问文件
			const url = window.URL.createObjectURL(new Blob([res.data]))
			// 创建一个隐藏的 <a> 元素用于触发下载
			const link = document.createElement('a')
			link.href = url
			link.setAttribute('download', '维信金科还款数据' + '.xlsx') // 设置下载文件名
			document.body.appendChild(link)
			link.click()
			// 清理工作：移除 <a> 元素和释放 URL 对象
			link.remove()
			window.URL.revokeObjectURL(url)
		})
	}

	const loadData = (parameter) => {
		const searchFormParam = JSON.parse(JSON.stringify(searchFormState))
		// createTime范围查询条件重载
		if (searchFormParam.createTime) {
			console.log('creatime', searchFormState.createTime)

			searchFormParam.startCreateTime = searchFormState.createTime[0]

			searchFormParam.endCreateTime = searchFormState.createTime[1]

			delete searchFormParam.createTime
		} else if (!searchFormParam.businessId) {
			// 获取当前日期时间
			const now = dayjs()

			searchFormParam.startCreateTime = now.startOf('day').format('YYYY-MM-DD HH:mm:ss')
			searchFormParam.endCreateTime = now.endOf('day').format('YYYY-MM-DD HH:mm:ss')
			// 获取当天的开始时间，并格式化为 YYYY-MM-DD HH:mm:ss 格式
			const startOfDay = now.startOf('day').format('YYYY-MM-DD HH:mm:ss')
			// 获取当天的结束时间，并格式化为 YYYY-MM-DD HH:mm:ss 格式
			const endOfDay = now.endOf('day').format('YYYY-MM-DD HH:mm:ss')
			// console.log(startOfDay,endOfDay);
			// console.log('searchFormParam',searchFormParam);

			// 将格式化后的开始时间和结束时间赋值给 createTime
			searchFormState.createTime = [startOfDay, endOfDay]
		}
		return dataWxjkHksjApi.dataWxjkHksjPage(Object.assign(parameter, searchFormParam)).then((data) => {
			return data
		})
	}
	// 重置
	const reset = () => {
		searchFormRef.value.resetFields()
		table.value.refresh(true)
	}
	// 删除
	const deleteDataWxjkHksj = (record) => {
		let params = [
			{
				id: record.id
			}
		]
		dataWxjkHksjApi.dataWxjkHksjDelete(params).then(() => {
			table.value.refresh(true)
		})
	}
	// 批量删除
	const deleteBatchDataWxjkHksj = (params) => {
		dataWxjkHksjApi.dataWxjkHksjDelete(params).then(() => {
			table.value.clearRefreshSelected()
		})
	}

	// // 处理日期变化（上海时区 → UTC）
	// const handleDateChange = (dates) => {
	// 	searchFormState.createTime = [
	// 		dayjs(dates[0]).utc().startOf('day'),  // 上海时间转UTC
	// 		dayjs(dates[1]).utc().endOf('day')
	// 	]
	// }

	onMounted(() => {
		// 获取当前登录人信息
		// dataWxjkHksjApi.getCallNumber().then((res) => {
		// 	formRef.onSetCallNumber(res)
		// 	formRef.value = res
		// })
	})
</script>
